package com.example.config;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Elasticsearch配置类
 */
@Configuration
public class ElasticsearchConfig {
    
    @Value("${spring.elasticsearch.uris:http://localhost:9200}")
    private String elasticsearchUrl;
    
    @Value("${spring.elasticsearch.username:elastic}")
    private String username;
    
    @Value("${spring.elasticsearch.password:changeme}")
    private String password;
    
    @Bean
    public RestClient elasticsearchClient() {
        // 解析URL
        String[] urlParts = elasticsearchUrl.replace("http://", "").split(":");
        String host = urlParts[0];
        int port = urlParts.length > 1 ? Integer.parseInt(urlParts[1]) : 9200;
        
        // 配置认证
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));
        
        return RestClient.builder(new HttpHost(host, port, "http"))
                .setHttpClientConfigCallback(httpClientBuilder ->
                        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider))
                .build();
    }
    
    @Bean
    public ElasticsearchClient elasticsearchJavaClient() {
        ElasticsearchTransport transport = new RestClientTransport(
                elasticsearchClient(), new JacksonJsonpMapper());
        return new ElasticsearchClient(transport);
    }
}